using System;
using System.Collections.Generic;
using System.Linq;
using Urs.Data.Domain.Stores;
using Urs.Data.Domain.Media;
using Urs.Services.Localization;
using Urs.Services.Media;

namespace Urs.Services.Stores
{
    public static class GoodsExtensions
    {
        public static Picture GetDefaultGoodsPicture(this Goods source, IPictureService pictureService)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            if (pictureService == null)
                throw new ArgumentNullException("pictureService");

            var picture = pictureService.GetPicturesByGoodsId(source.Id, 1).FirstOrDefault();
            return picture;
        }

        public static string FormatStockMessage(this Goods goods, ILocalizationService localizationService)
        {
            if (goods == null)
                throw new ArgumentNullException("goods");

            if (localizationService == null)
                throw new ArgumentNullException("localizationService");

            string stockMessage = string.Empty;

            if (goods.ManageStockEnabled)
            {
                if (goods.StockQuantity > 0)
                {
                    stockMessage = string.Format(localizationService.GetResource("Goodss.Availability.InStockWithQuantity"), goods.StockQuantity);
                }
                else
                {
                    stockMessage = localizationService.GetResource("Goodss.Availability.OutOfStock");
                }
            }
            return stockMessage;
        }

        public static bool GoodsTagExists(this Goods goods,
            int goodsTagId)
        {
            if (goods == null)
                throw new ArgumentNullException("goods");

            bool result = goods.GoodsTags.ToList().Find(pt => pt.GoodsTagId == goodsTagId) != null;
            return result;
        }

        public static string FormatSku(this Goods goods, string selectedAttributes = null, IGoodsSpecParser goodsSpecParser = null)
        {
            if (goods == null)
                throw new ArgumentNullException("goods");

            string sku = goods.Sku;

            if (!string.IsNullOrEmpty(selectedAttributes))
            {
                if (goodsSpecParser == null)
                    throw new ArgumentNullException("goodsSpecParser");

                var combination = goods
                    .GoodsSpecCombinations
                    .FirstOrDefault(x => goodsSpecParser.AreGoodsSpecsEqual(x.AttributesXml, selectedAttributes));
                if (combination != null)
                {
                    sku = combination.Sku;
                }
            }

            if (String.IsNullOrEmpty(sku))
                sku = goods.Sku;

            return sku;

        }

    }
}
